/**
 * 
 */
package db;

import java.sql.ResultSet;
import java.sql.SQLException;

import models.StatusResponse;
import models.UserInfo;
import util.constants.RegistrationConstants;
import db.queryBuilders.UserAccountQueryBuilder;

/**
 * @author Teja
 * 
 */
public class UserAccountDatabaseBean extends DatabaseBean {

	public UserAccountDatabaseBean() {
		
		super();
	}
	
	public StatusResponse RegisterUser(UserInfo userInfo) {

		StatusResponse response = new StatusResponse();

		// user already exists
		if (DoesUsernameExistInDB(userInfo.getUsername())) {
			response.addResponseMessage(RegistrationConstants.USER_ALREADY_REGISTERED);
			response.setSucess(false);

		// email already exists
		} else if (DoesEmailExistInDB(userInfo.getEmailAddress())) {
			response.addResponseMessage(RegistrationConstants.EMAIL_ALREADY_REGISTERED);
			response.setSucess(false);
		
		// user name or email address do not exist yet
		} else {

			String queryUserTable = UserAccountQueryBuilder.RegisterUsersTable(
					userInfo.getUsername(), userInfo.getPassword());
			String queryUserRoleTable = UserAccountQueryBuilder
					.RegisterUserRoleTable(userInfo.getUsername(),
							userInfo.getUserRole());
			String queryUserProfileTable = UserAccountQueryBuilder
					.RegisterUserProfileTable(userInfo);
			String queryAddressTable = UserAccountQueryBuilder
					.RegisterAddressTable(userInfo.getAddress());

			try {
				// adding user to DB tables
				getStmt().executeUpdate(queryUserTable);
				getStmt().executeUpdate(queryUserRoleTable);
				getStmt().executeUpdate(queryUserProfileTable);
				getStmt().executeUpdate(queryAddressTable);

			} catch (SQLException e) {
				e.printStackTrace();
			}

			response.addResponseMessage(RegistrationConstants.REGISTERED_SUCESS);
			response.setSucess(true);
		}

		return response;
	}

	private boolean DoesEmailExistInDB(String emailAddress) {

		boolean doesExist = false;

		String query = UserAccountQueryBuilder.DoesEmailExistInDBQuery(emailAddress);

		try {
			ResultSet rs = getStmt().executeQuery(query);
			if (rs.next()) {
				doesExist = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return doesExist;
	}

	private boolean DoesUsernameExistInDB(String username) {
		boolean userExists = false;

		String query = UserAccountQueryBuilder.DoesUserExistInDBQuery(username);
		try {
			ResultSet rs = getStmt().executeQuery(query);
			if (rs.next()) {
				rs.getString("username");
				userExists = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userExists;
	}
	
	public static void main(String args[]) {
		UserAccountDatabaseBean bean = new UserAccountDatabaseBean();
		System.out.println(bean.DoesUsernameExistInDB("tejas24"));
		
	}
}
